package action.weixin;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;

import security.MySecurityContextHandle;
import service.interf.IWxMember;

import com.opensymphony.xwork2.ActionSupport;
import common.wx.WxAuth;

import dao.pojo.WxMember;

public class WeixinAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	public static Map<String, String> stateMap = new HashMap<String, String>();
	private IWxMember iWxMember;
	private String code;
	private String pn;
	private String url;
	private String param;

	public void setParam(String param) {
		this.param = param;
	}

	public void setiWxMember(IWxMember iWxMember) {
		this.iWxMember = iWxMember;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getPn() {
		return pn;
	}

	public void setPn(String pn) {
		this.pn = pn;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String base() {
		if (null != MySecurityContextHandle.getUserId()) {
			url = getRedirectUrl();
			return SUCCESS;
		}
		if (null == code) {
			paramToPn();
			url = WxAuth.getAuthUrl(WxAuth.AUTH_TYPE_BASE, getAuthNameBase(0)
					+ "," + pn);
		} else {
			WxMember wxMember = null;
			try {
				wxMember = iWxMember.add(code);
			} catch (Exception e) {
			}
			if (null != wxMember) {
				if (wxMember.getIsAuth()) {
					url = getRedirectUrl();
					MySecurityContextHandle.setOpenId(wxMember.getOpenId());
					MySecurityContextHandle.addAuthentication(wxMember
							.getOpenId(), wxMember.getOpenId());
				} else {
					url = WxAuth.getAuthUrl(WxAuth.AUTH_TYPE_USERINFO,
							getAuthNameBase(1) + "," + pn);
				}
			} else {
				url = WxAuth.getAuthUrl(WxAuth.AUTH_TYPE_BASE,
						getAuthNameBase(0) + "," + pn);
			}
		}
		return SUCCESS;
	}

	public String userinfo() {
		if (null == code) {
			paramToPn();
			url = WxAuth.getAuthUrl(WxAuth.AUTH_TYPE_USERINFO,
					getAuthNameBase(1) + "," + pn);
		} else {
			WxMember wxMember = null;
			try {
				wxMember = iWxMember.add(code);
			} catch (Exception e) {
			}
			url = getRedirectUrl();
			MySecurityContextHandle.setOpenId(wxMember.getOpenId());
			MySecurityContextHandle.addAuthentication(wxMember.getOpenId(),
					wxMember.getOpenId());
		}
		return "success";
	}

	private void paramToPn() {
		if (!"".equals(param)) {
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			stateMap.put(uuid, param);
			pn = uuid;
		}
	}

	@SuppressWarnings("unchecked")
	private String getRedirectUrl() {
		String search = null;
		String pageName = null;
		String param = stateMap.remove(pn);
		if (!StringUtils.isEmpty(param)) {
			JSONObject jo = JSONObject.fromObject(param);
			Set<String> keys = jo.keySet();
			for (String key : keys) {
				if ("pageName".equals(key)) {
					pageName = jo.getString(key);
					continue;
				}
				if ("isNeedWin".equals(key)) {
					continue;
				}
				if (null == search) {
					search = "?";
				} else {
					search += "&";
				}
				search += key + "=" + jo.getString(key);
			}
		}
		if (StringUtils.isEmpty(pageName))
			pageName = "/mobi/rotate.html";
		if (StringUtils.isEmpty(search))
			search = "";
		url = getServerPath() + pageName + search;
		return url;
	}

	private String getAuthNameBase(int baseType) {
		HttpServletRequest request = ServletActionContext.getRequest();
		String serverName = request.getServerName();
		String str = "fw";
		if (null != serverName) {
			if (serverName.contains("www.91boogoo.com")) {
				str = "fw_91boogoo_com";
			} else if (serverName.contains("www.91boogoo.cn")) {
				str = "fw_91boogoo_cn";
			}
		}
		if (baseType == 1)
			return str + "_userinfo";
		else
			return str + "_base";
	}

	private String getServerPath() {
		HttpServletRequest request = ServletActionContext.getRequest();
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort() + request.getContextPath();
	}

}
